package team.fourth.combat.commen.utils;

import cn.hutool.core.bean.BeanUtil;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class SignatureUtil {

    public static String sign(Object obj){
        Map<String, Object> map = BeanUtil.beanToMap(obj);
        return DigestUtils.md5Hex(getSignContent(map).getBytes());
    }

    private static String getSignContent(Map<String, Object> sortedParams) {
        StringBuilder content = new StringBuilder();
        List<String> keys = new ArrayList<String>(sortedParams.keySet());
        Collections.sort(keys);
        int index = 0;
        for (String key : keys) {
            Object value = sortedParams.get(key);
            if (null != value) {
                content.append(index == 0 ? "" : "&").append(key).append("=").append(value);
                index++;
            }
        }
        //name=jack&sex=1&age=19
        return content.toString();
    }

}
